package com.llsydn.demo.music;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import com.llsydn.hello.R;

/**
 * @author lilinshen
 * @title music的service
 * @description 请填写相关描述
 * @date 2018/9/29 14:46
 */
public class MusicService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getStringExtra("action");
        if ("play".equals(action)) {
            playMusic();
        } else if ("pause".equals(action)) {
            pauseMusic();
        } else if ("stop".equals(action)) {
            stopMusic();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //在死亡之前停止音乐
        stopMusic();
    }

    private MediaPlayer player;

    /**
     * 播放音乐
     */
    public void playMusic() {
        if (player == null) {
            player = MediaPlayer.create(this, R.raw.water_hander);
        }
        player.start();
    }

    /**
     * 停止音乐
     */
    public void stopMusic() {
        if (player != null) {
            player.stop();//停止
            player.reset();//重置
            player.release();//释放资源
            player = null;
        }
    }

    /**
     * 暂停音乐
     */
    public void pauseMusic() {
        if (player != null && player.isPlaying()) {
            player.pause();
        }
    }

    /**
     * 退出音乐
     */
    public void exitMusic() {
        stopMusic();
        // finish();
    }
}
